import { UseGuards } from '@nestjs/common';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UserEntity } from '@app/prisma/entitys/user.entity';
import { GqlAuthGuard, GqlCurrentUser } from './auth.guard';
import { ForbiddenError } from '@nestjs/apollo';
import { AuthService } from './auth.service';
import { PrismaService } from '@app/prisma';
import { HashService } from '@app/hash';
import { ProfileEntity } from '@app/prisma/profile.entity';

@Resolver(of => UserEntity)
export class AuthResolver {
    constructor(
        private readonly prismaService: PrismaService,
        private readonly authService: AuthService,
        private readonly hashService: HashService
    ) { }
    @Mutation(() => ProfileEntity)
    @UseGuards(GqlAuthGuard)
    updPwd(
        @Args("pwd") pwd: string,
        @Args("before") before: string,
        @GqlCurrentUser() user: UserEntity
    ) {
        if (user.profile.password !== this.hashService.cryptoPassword(before)) {
            throw new ForbiddenError("密码错误")
        }
        return this.prismaService.profile.update({
            where: {
                id: user.profileId
            },
            data: {
                password: this.hashService.cryptoPassword(pwd)
            }
        })
    }

    @Query(() => [String])
    @UseGuards(GqlAuthGuard)
    getRouter(
        @GqlCurrentUser() user: UserEntity
    ) {
        if (user.router === "admin") {
            return ["商家管理", "商品管理", "订单中心", "评论管理"]
        }
        if (user.router === "shop") {
            return ["我的商品", "商品订单", "商品评论"]
        }
        return ["订单列表", "我的订单"]
    }

    @Mutation(() => UserEntity)
    async authWx(@Args("code") weUnionid: string) {
        const find = await this.prismaService.profile.findUnique({ where: { weUnionid } });
        let user: UserEntity;
        if (!!find) {
            user = await this.prismaService.user.findFirst({ where: { profile: { weUnionid } }, include: { profile: true } })
        } else {
            user = await this.prismaService.user.create({
                data: {
                    account: weUnionid,
                    hash_key: this.hashService.createUid(),
                    profile: {
                        create: {
                            weUnionid,
                            password: weUnionid
                        }
                    },
                    name: "未设置用户名"
                },
                include: {
                    profile: true
                }
            })
        }
        user.token = this.authService.getToken(user).access_token;
        return user
    }

    @Query(() => UserEntity)
    @UseGuards(GqlAuthGuard)
    currentUser(
        @GqlCurrentUser() user: UserEntity
    ) {
        return user;
    }

    @Mutation(() => UserEntity)
    async auth(
        @Args("account") account: string,
        @Args("password") password: string
    ) {
        const user: UserEntity = await this.prismaService.user.findUnique({
            where: {
                account,
                profile: {
                    password: this.hashService.cryptoPassword(password)
                }
            },
            include: {
                profile: true
            }
        })
        if (!user) throw new ForbiddenError("找不到账户")
        user.href = "/"
        user.token = this.authService.getToken(user).access_token
        return user;
    }

    @Mutation(() => UserEntity)
    async registry(
        @Args("account") account: string,
        @Args("password") password: string
    ) {
        if (!!await this.prismaService.user.findUnique({ where: { account } })) throw new ForbiddenError("账号已被注册");
        const user: UserEntity = await this.prismaService.user.create({
            data: {
                account,
                name: "未设置用户名",
                hash_key: this.hashService.createUid([account, password]),
                profile: {
                    create: {
                        password: this.hashService.cryptoPassword(password)
                    }
                }
            },
            include: {
                profile: true
            }
        })
        user.token = this.authService.getToken(user).access_token;
        return user;
    }

    @Query(() => UserEntity)
    @UseGuards(GqlAuthGuard)
    viewer(
        @GqlCurrentUser() user: UserEntity
    ) {
        return user
    }

}
